<template>
  <view class="login_page">
    <image
      src="https://diancan-1252107261.cos.accelerate.myqcloud.com/yiliao/denglu-yemian.jpg"
      mode="aspectFill"
    />

    <view class="login" @click="goLogin"> 授权登录 </view>
  </view>
</template>

<script setup lang="ts">
import { wxLoginApi } from "@/http/api";
//登录授权
const goLogin = () => {
  uni.getUserProfile({
    lang: "zh_CN",
    desc: "获取用户授权",
    success: (res) => {
      console.log(res);
      const { avatarUrl, nickName } = res.userInfo;
      uni.login({
        success: (result) => {
          //调用真实的用户登录方法
          console.log(result);
          wxLogin(avatarUrl, nickName, result.code);
        },
        fail: (fail) => {
          return Promise.reject("授权失败");
        },
      });
    },
    fail: (fail) => {
      return Promise.reject("授权失败");
    },
  });
};

const wxLogin = async (avatarUrl: string, nickName: string, code: string) => {
  const obj = {
    avatarUrl,
    nickName,
    code,
    appid: "wxb61621e772a9f027",
    secret: "8207f36e4edaccff23ea953bfbfd94c6",
  };

  //开始调用登录接口api
  const res = await wxLoginApi(obj);
  console.log("用户登录返回：", res);
  //保存token
  uni.setStorageSync("wxuser", res.data.data);
  //返回上一个页面
  setTimeout(() => {
    uni.navigateBack({
      delta: 1,
    });
  }, 600);
};
</script>

<style lang="scss">
.login_page {
  height: 100vh;
  position: relative;

  image {
    width: 100%;
    height: 100%;
  }

  .login {
    position: absolute;
    left: 50%;
    bottom: 30%;
    background: #4677e2;
    width: 300rpx;
    height: 80rpx;
    border-radius: 8rpx;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    transform: translate3d(-50%, -30%, 0);
  }
}
</style>
